
(function($) {
    $(function() {         
        
        function selected_category(node) {
            var category = jq(node);
            var category_path = [];            
            if (category != null) {
                category_path.push(category.attr('id'));
                category.parents('li').each(function() {
                    category_path.push(jq(this).attr('id'));
                });                 
            };            
            return category_path;
        };
        function selected_category_with_labels(node) {
            var category = jq(node);
            var category_path = [];            
            if (category != null) {
                category_path.push(category.find('a:first').text());
                category.parents('li').each(function() {
                    category_path.push(jq(this).find('a:first').text())
                });                 
            };                     
            return category_path;
        };
        function category_selected_deselected(node, tree_obj, deselecting) {
            var selected_keywords = [];
            jq('select#subject_selected option').each(function() { 
                selected_keywords.push(this.value)
            });
            var selected_categories = [];
            var node_category_str = selected_category(node).join(',');      
            
            if (deselecting) { // Deselect a selected node/category 
                var allCatArray = [];
                pathelement = jq('input#resourcecategorypath');
                var pathelementval = pathelement.val();
                var oldCatArray = pathelementval.split(';');                 
                
                var node_category_str_labels = selected_category_with_labels(node).join(',');
                var reversedPath2 = node_category_str_labels.toString().split(',').reverse().join(','); 
                reversedPath2 = reversedPath2.replace('Root node,', '');
                reversedPath2 = reversedPath2.split(',').join(' -> ');
                
                for(i in oldCatArray) {
                    if (String(oldCatArray[i]).trim() == String(reversedPath2).trim()) {
                        oldCatArray.splice(i, 1);
                    }
                }
                
                pathelement.val(oldCatArray.join(";"));
            } else { 
                setTimeout(function() {
                    // Delay to allow a category path to be selected.        
                }, 1000);
            }
            
            var count = 1; // flag to stop looping
            
            jq.each(tree_obj.selected_arr, function() { 
                sc = selected_category(this);
                if (deselecting) { 
                    if (sc.join(',') == node_category_str) { 
                        // skip currently deselected node                        
                        return
                    }
                } else {
                    // Assign the selected path ID to the input field
                    pathelement = jq('input#resourcecategorypath');
                    var pathelementval = pathelement.val();
                    pathelementval = (pathelementval == '') ? '' : pathelementval + '; ';
                    var reversedPath = node_category_str.toString().split(',').reverse().join(','); 
                    reversedPath = reversedPath.replace('root-node,', '');
                    //pathelement.val(pathelementval + reversedPath);
                    
                    // Get the descriptive path labels
                    var node_category_str_labels = selected_category_with_labels(node).join(',');
                    var reversedPath2 = node_category_str_labels.toString().split(',').reverse().join(','); 
                    reversedPath2 = reversedPath2.replace('Root node,', '');
                    reversedPath2 = reversedPath2.split(',').join(' -> ');
                    
                    // Prevent saving the path while creating a new category
                    if ( reversedPath2.toLowerCase().indexOf( "New category".toLowerCase() ) == -1 ) {
                        pathelement.val(pathelementval + reversedPath2);
                    }              
                    
                }
                selected_categories[selected_categories.length] = sc;
                return (count > 1) // Will stop running after the first iteration to avoid saving duplicates
            });
            
            jq.ajax({
                    type:'POST',
                    url:portal_url+'/vtc-list-keywords_by_categories',
                    data:{  categories: selected_categories,
                            selected: selected_keywords
                         },
                    success:function(data) {
                                var $master = jq('select#subject_unselected');
                                $master.empty();
                                jq.each(data.keywords, function() { $master.append('<option value="'+this+'">'+this+'</option>') });
                            },
                    dataType: 'json',
                    traditional: true
            })
        };
        
        /**
        * On page load, highlight all the previously saved categories
        */
        function highlight_selected_category() {
            var pathelementval = '';
            setTimeout(function() {
                pathelement = jq('input#resourcecategorypath'); 
                pathelementval = pathelement.val();               
            }, 1000);
            
            setTimeout(function() {
                var allCatArray = [];
                var oldCatArray = pathelementval.split(';');
                
                jq("ul#VTCFilterTree ul.ltr li#root-node ul").children().each(function(index,value) { 
                    var currCatText = jq(this).find('a:first').text(); 
	                
	                for (i in oldCatArray) {
                        var currPath = oldCatArray[i].split('->');
                        for (m in currPath) {
                            if (currPath[m].toLowerCase().trim() == currCatText.toLowerCase().trim()) {
                                jq(this).attr('class', 'open');
	                            jq(this).find('a:first').attr('class', 'clicked');
                            }
                        }
                    }
	                
                }); 
            }, 1000);           
        };
        $(document).ready(function () {
            var $tree = jq('ul#VTCFilterTree');
            
            $tree.tree({
                        data  : {
                          type  : "json",
                          url   : portal_url+"/@@vtc-categories-tree.json",
                          async : false
                        },
                        lang : {
                            new_node    : "New category"
                        },
                        rules: {
                            multiple   : "on",
                            clickable  : [ "folder" ],
                            creatable  : "none",
                            deletable  : "none",
                            renameable : "none",
                            draggable  : "none",
                            droppable  : "none"
                        },
                        callback : {
                            onselect   : function(node, tree_obj) {
                                            category_selected_deselected(node, tree_obj, false);
                                         },
                            ondeselect : function(node, tree_obj) {
                                            category_selected_deselected(node, tree_obj, true);
                                         },
                            oncreate: function(node) { jq(node).attr('rel', 'folder') },
                            onrename: function(node, lang, tree_obj, rb) {
                                old_id = node.id // may be undefined (new node)
                                new_name = jq(node).children("a:visible").text();
                                // shared code. Server determines if creating/renaming by the old_name value
                                jq.ajax({
                                     type: 'POST',
                                     url: "vtc-category-added-renamed",
                                     data: 
                                        {
                                          'category_path': selected_category(node),
                                          'old_id': old_id,
                                          'new_name': new_name
                                        },
                                     success :  
                                        function(data) {
                                            jq.jGrowl(data.msg, { life: 1500 });
                                            // set/change node id
                                            if (data.result) {
                                                node.id = data.new_id
                                            }
                                        },
                                     dataType: 'json',
                                     traditional: true
                                })
                            },
                            beforedelete: function(node, tree_obj) {
                                jq.ajax({
                                     type: 'POST',
                                     url: "vtc-category-removed",
                                     data: 
                                        {
                                          'category_path': selected_category(node)
                                        },
                                     success :  
                                        function(data) {
                                            jq.jGrowl(data.msg, { life: 3000 });
                                        },
                                     dataType: 'json',
                                     traditional: true
                                });
                                return true;
                            }
                        } 
                    });
            }); highlight_selected_category();
        })
})(jQuery);
